package controller.macro;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Giuseppe Fusco (fusgius19@gmail.com)
 *
 */
public class Macro {

	private String name;
	private List<Condition<?>> preconditions = new ArrayList<Condition<?>>();
	private List<Condition<?>> postconditions = new ArrayList<Condition<?>>();
	
	public Macro(String name){
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public final void addPrecondition(Condition<?> condition){
		preconditions.add(condition);
	}
	
	public final void removePrecondition(Condition<?> condition){
		preconditions.remove(condition);
	}
	
	public final void removePrecondition(String name){
		for(Condition<?> c: preconditions)
			if(c.getName().equals(name))
				preconditions.remove(c);
	}
	
	public final void addPostcondition(Condition<?> condition){
		postconditions.add(condition);
	}
	
	public final void removePostcondition(Condition<?> condition){
		postconditions.remove(condition);
	}
	
	public final void removePostcondition(String name){
		for(Condition<?> c: postconditions)
			if(c.getName().equals(name))
				postconditions.remove(c);
	}
	
	private final boolean IsValidPrecondition()throws ConditionException{
		for(Condition<?> c: preconditions){
			if(!c.perform())
				throw new ConditionException(c.getName());
		}
		return true;
	}
	
	private boolean IsValidPostcondition()throws ConditionException{
		for(Condition<?> c: postconditions){
			if(!c.perform())
				throw new ConditionException(c.getName());
		}
		return true;
	}
	
	public final boolean execute() throws ConditionException{
		return IsValidPrecondition() && IsValidPostcondition();
	}
	
	public final int getPreconditionSize(){
		return preconditions.size();
	}
	
	public final int getPostconditionSize(){
		return postconditions.size();
	}
}
